package com.hnevc.xiaoming.initutil;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtil {
    public static OkHttpUtil okHttpUtil;
    public static final String HEAD_URL = "";
    private static final String TAG = "OkHttpUtil";
    public OkHttpUtil() {
    }

    public static OkHttpUtil getOkHttpUtil() {
        if (okHttpUtil == null) {
            okHttpUtil = new OkHttpUtil();
        }
        return okHttpUtil;
    }

    /**
     * 发送请求，需在新线程调用
     *
     * @param url  请求地址，注意只需要传入http://10.1.58.220:8081/后的内容即可
     * @param body 请求体
     * @return 服务端返回的json数据
     * @throws Exception
     */
    public JSONObject getResponseByPOST(String url, String body) throws IOException, JSONException {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody requestBody;

        requestBody = RequestBody.create(mediaType, body);

        Request request = new Request.Builder()
                .url(HEAD_URL + url)
                .post(requestBody)
                .build();

        Response execute = client.newCall(request).execute();
        JSONObject jsonObject = new JSONObject(execute.body().string());
        return jsonObject;
    }

    /**
     * 发送请求，需在新线程调用
     *
     *
     * @param faa
     * @param url  请求地址，注意只需要传入http://10.1.58.220:8081/后的内容即可
     * @return 服务端返回的json数据
     * @throws Exception
     */
    public String getResponseByGET(String faa, String url) throws IOException, JSONException {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody requestBody = RequestBody.create(mediaType, "");

        Request request = new Request.Builder()
                .url(HEAD_URL + url)
                .post(requestBody)
                .build();

        Response execute = client.newCall(request).execute();

        return execute.body().string();

    }
}
